package com.hzy.utils.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.hzy.constant.ConfigConstants;
import com.hzy.utils.DateUtils;

import java.math.BigDecimal;

/**
 * Created by admin on 2017/12/3.
 */
public class AlipayUtils {
    private AlipayUtils() throws Exception {
        throw new RuntimeException("no instants");
    }

    public static String getOrderInfo(String outTradeNo, String content, String subject, String price){
        //实例化客户端,参数待修改
        AlipayClient alipayClient = new DefaultAlipayClient(ConfigConstants.ALIPAY_SERVER_URL, ConfigConstants.ALIPAY_APP_ID,
                ConfigConstants.ALIPAY_APP_PRIVATE_KEY, ConfigConstants.ALIPAY_FORMAT, ConfigConstants.ALIPAY_CHARSET, ConfigConstants.ALIPAY_PUBLIC_KEY, ConfigConstants.ALIPAY_SIGN_TYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(content);   //内容
        model.setSubject(subject); //标题
        model.setOutTradeNo(outTradeNo);  //订单号
        model.setTimeoutExpress("30m"); //
//        model.setTotalAmount("0.01");
        model.setTotalAmount(price);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(ConfigConstants.ALIPAY_NOTIFY_URL);
//            RedisUtils.set(outTradeNo, user_id + "," + price + "," + coinNum);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 发起退款
     */
    public static AlipayTradeRefundResponse getAliOrderRefund(int userId, BigDecimal totalFee, String refundDesc,
                                             String outTradeNo, String outRefundNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(ConfigConstants.ALIPAY_SERVER_URL,
                ConfigConstants.ALIPAY_APP_ID, ConfigConstants.ALIPAY_APP_PRIVATE_KEY, ConfigConstants.ALIPAY_FORMAT, ConfigConstants.ALIPAY_CHARSET, ConfigConstants.ALIPAY_PUBLIC_KEY, ConfigConstants.ALIPAY_SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"refund_amount\":\"" + totalFee + "\"," +
                "\"refund_currency\":\"CNY\"," +
                "\"refund_reason\":\"" + refundDesc + "\"," +
                "\"out_request_no\":\"" + outRefundNo +"\"," +
                "\"gmt_refund_pay\": \"" + DateUtils.getTime() + "\"," +
                "\"operator_id\":\"" + userId + "\"" +
                "  }");

        return alipayClient.execute(request);
//        AlipayTradeRefundResponse response = alipayClient.execute(request);
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//            return response.getBody();
//        } else {
//            System.out.println("调用失败");
//            return "{\"msg\":\"调用失败\"}";
//        }
    }


    // -------------------------------------------------------- 商品订单支付 --------------------------------------------------------


    /**
     * 发起支付，得到签名
     * @param totalAmount 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
     * @param body 支付描述
     * @param subject  商品的标题/交易标题/订单标题/订单关键字等
     * @param outTradeNo  订单号
     * @return
     */
    public static String getGoodsOrderInfo(BigDecimal totalAmount, String body, String subject, String outTradeNo) {
        //实例化客户端,参数待修改
        AlipayClient alipayClient = new DefaultAlipayClient(ConfigConstants.ALIPAY_SERVER_URL, ConfigConstants.ALIPAY_APP_ID,
                ConfigConstants.ALIPAY_APP_PRIVATE_KEY, ConfigConstants.ALIPAY_FORMAT, ConfigConstants.ALIPAY_CHARSET, ConfigConstants.ALIPAY_PUBLIC_KEY,
                ConfigConstants.ALIPAY_SIGN_TYPE);
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        //对一笔交易的具体描述信息
        model.setBody(body);
        //商品的标题/交易标题/订单标题/订单关键字等
        model.setSubject(subject);
        //订单号
        model.setOutTradeNo(outTradeNo);
        //笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        model.setTimeoutExpress(ConfigConstants.ALIPAY_EXPIRE_TIME);
        //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        model.setTotalAmount(String.valueOf(totalAmount));
        System.out.println("支付金额：" + model.getTotalAmount());
        //销售产品码，商家和支付宝签约的产品码，为固定值
        model.setProductCode(ConfigConstants.ALIPAY_PRODUCT_CODE);
        request.setBizModel(model);
        request.setNotifyUrl(ConfigConstants.ALIPAY_GOODS_NOTIFY_URL);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return ConfigConstants.ERROR_LOW;
        }
    }




    /**
     * 发起退款
     */
    public static String getGoodsAliOrderRefund(int userId, BigDecimal totalFee, String refundDesc,
                                             String outTradeNo, String outRefundNo) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(ConfigConstants.ALIPAY_SERVER_URL,
                ConfigConstants.ALIPAY_APP_ID, ConfigConstants.ALIPAY_APP_PRIVATE_KEY, ConfigConstants.ALIPAY_FORMAT, ConfigConstants.ALIPAY_CHARSET, ConfigConstants.ALIPAY_PUBLIC_KEY, ConfigConstants.ALIPAY_SIGN_TYPE);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"refund_amount\":\"" + totalFee + "\"," +
                "\"refund_currency\":\"CNY\"," +
                "\"refund_reason\":\"" + refundDesc + "\"," +
                "\"out_request_no\":\"" + outRefundNo +"\"," +
                "\"gmt_refund_pay\": \"" + DateUtils.getTime() + "\"," +
                "\"operator_id\":\"" + userId + "\"" +
                "  }");
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return response.getBody();
        } else {
            System.out.println("调用失败");
            return "{\"msg\":\"调用失败\"}";
        }
    }

}